package com.soup.lab.tools.faker.source;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * 可分页获取的迭代器
 * @param <E>
 */
public abstract class PageableIterator<E> implements Iterator<E> {
    /**
     * 每次读取的条数
     */
    protected final int pageSize;
    /**
     * 读取到的每一页的缓存记录
     */
    protected Object[] cache;
    /**
     * 是否耗尽
     */
    protected boolean exhausted;
    /**
     * 最近一次读取的记录数，不会超过页的大小 {@link #pageSize}
     */
    protected int cacheMaxIndex;
    /**
     * 当前读取的下标
     */
    protected int currentIndex;

    public PageableIterator(int pageSize) {
        this.pageSize = pageSize;
        this.cacheMaxIndex = -1;
        this.currentIndex = 0;
    }

    @Override
    public boolean hasNext() {
        if (cacheMaxIndex < 0) {
            if (exhausted) {
                return false;
            }
            readPage();
        }
        return cacheMaxIndex >= 0;
    }

    @Override
    public E next() {
        if (cacheMaxIndex-- < 0) {
            throw new NoSuchElementException();
        }
        return (E) cache[currentIndex++];
    }

    abstract protected void readPage();

}
